package io.adminboot.web;

import io.adminboot.domain.param.JqGridParam;
import io.adminboot.domain.vo.PageVO;
import io.adminboot.entity.SysRole;
import io.adminboot.service.SysRoleMenuService;
import io.adminboot.service.SysRoleService;
import io.adminboot.system.annotation.AddSysLog;
import io.adminboot.system.validator.ValidatorUtils;
import io.adminboot.utils.Constant;
import io.adminboot.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 角色管理
 * 
 */
@RestController
@RequestMapping("/sys/role")
public class SysRoleController extends AbstractController {
	@Autowired
	private SysRoleService sysRoleService;
	@Autowired
	private SysRoleMenuService sysRoleMenuService;

	/**
	 * 角色列表
	 */
	@GetMapping("/list")
//	@RequiresPermissions("sys:role:list")
	public R list(JqGridParam param) {
		// 如果不是超级管理员，则只查询自己创建的角色列表
		Long createUserId = null;
		if (getUserId() != Constant.SUPER_ADMIN) {
			createUserId = getUserId();
		}

		PageVO page = sysRoleService.queryPage(param.getPageNum(), param.getPageSize(), createUserId);

		return R.ok().put("page", page);
	}

	/**
	 * 角色列表
	 */
	@GetMapping("/select")
//	@RequiresPermissions("sys:role:select")
	public R select() {
		// 如果不是超级管理员，则只查询自己所拥有的角色列表
		Long createUserId = null;
		if (getUserId() != Constant.SUPER_ADMIN) {
			createUserId = getUserId();
		}
		List<SysRole> list = sysRoleService.selectByCreateUserId(createUserId);

		return R.ok().put("list", list);
	}

	/**
	 * 角色信息
	 */
	@GetMapping("/info/{roleId}")
//	@RequiresPermissions("sys:role:info")
	public R info(@PathVariable("roleId") Long roleId) {
		SysRole role = sysRoleService.selectById(roleId);

		// 查询角色对应的菜单
		List<Long> menuIdList = sysRoleMenuService.queryMenuIdList(roleId);
		role.setMenuIdList(menuIdList);

		return R.ok().put("role", role);
	}

	/**
	 * 保存角色
	 */
	@AddSysLog("保存角色")
	@PostMapping("/save")
//	@RequiresPermissions("sys:role:save")
	public R save(@RequestBody SysRole role) {
		ValidatorUtils.validateEntity(role);

		role.setCreateUserId(getUserId());
		sysRoleService.save(role);

		return R.ok();
	}

	/**
	 * 修改角色
	 */
	@AddSysLog("修改角色")
	@PostMapping("/update")
//	@RequiresPermissions("sys:role:update")
	public R update(@RequestBody SysRole role) {
		ValidatorUtils.validateEntity(role);

		role.setCreateUserId(getUserId());
		sysRoleService.update(role);

		return R.ok();
	}

	/**
	 * 删除角色
	 */
	@AddSysLog("删除角色")
	@PostMapping("/delete")
//	@RequiresPermissions("sys:role:delete")
	public R delete(@RequestBody Long[] roleIds) {
		sysRoleService.deleteByRoleIds(roleIds);

		return R.ok();
	}
}
